package com.unione.map.view.act

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.unione.map.databinding.ActivityLoginBinding
import com.unione.map.mmkv.AppConfigManager
import com.unione.unione_base.view.AppBaseActivity
import com.unione.unione_protocol.UnioneRobotAppRepository
import kotlinx.coroutines.launch

class LoginActivity : AppBaseActivity() {

    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        val rootView = binding.root
        setContentView(rootView)
        initListeners()
    }

    private fun initListeners() {
        binding.btnLogin.setOnClickListener {
            val name = binding.tvName.text.toString().trim()
            val pwd = binding.tvPassword.text.toString().trim()
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
                ToastUtils.showLong("请输入正确的账号和密码")
                return@setOnClickListener
            }
            login(name, pwd)
        }
    }

    private fun login(name: String, pwd: String) {
        lifecycleScope.launch {
            try {
                val rsp = UnioneRobotAppRepository.login(name, pwd)
                if (rsp.isSuccess()) {
                    val userInfo = rsp.data
                    if (userInfo != null) {
                        AppConfigManager.setUserInfo(userInfo)
                        startActivity(Intent(mContext, MainActivity::class.java))
                    }
                } else {
                    ToastUtils.showLong(rsp.message)
                }
            } catch (e: Exception) {

            }
        }

    }
}